/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package testing_class;

import bsh.EvalError;
import gui.JListModelOutputStream;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import stendcontrol.Configurator;
import stendcontrol.DataTract;
import stendcontrol.Experiment;
import stendcontrol.ExperimentContainer;
import stendcontrol.Research;
import stendcontrol.ResearchContainer;
import stendcontrol.ResearchInterpreter;

/**
 *
 * @author minaev
 */
public class ResearchContainer_Test extends javax.swing.JFrame {

    ExperimentContainer ec = new ExperimentContainer();
    ResearchContainer rc = new ResearchContainer();
    DataTract dt = new DataTract();
    ResearchInterpreter ri;
    JListModelOutputStream list_outstream = new JListModelOutputStream();
    MouseListener ml_listresearchers = new MouseListener() {
        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getSource().getClass() == JList.class) {
                JList jl = (JList) e.getSource();
                int si = jl.getSelectedIndex();
                if (si != -1) {
                    if (e.getClickCount() == 2) {
                        try {
                            ri.startResearch(rc.getResearch(si));
                        } catch (EvalError ex) {
                            Logger.getLogger(
                                    ResearchContainer_Test.class.getName()).
                                    log(Level.SEVERE, null, ex);
                        }
                    } else if (e.getClickCount() == 1) {
                        ta.setText(rc.getResearch(si).getCode());
                    }
                }
            }
        }

        @Override
        public void mousePressed(MouseEvent e) {
        }

        @Override
        public void mouseReleased(MouseEvent e) {
        }

        @Override
        public void mouseEntered(MouseEvent e) {
        }

        @Override
        public void mouseExited(MouseEvent e) {
        }
    };

    /**
     * Creates new form ResearchContainer_Test
     */
    public ResearchContainer_Test() {
        initComponents();
//        UDP_Fluder uf;
//        try {
//            uf = new UDP_Fluder("127.0.0.255", 10);
//            uf.start();
//        } catch (SocketException ex) {
//            Logger.getLogger(ResearchContainer_Test.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (UnknownHostException ex) {
//            Logger.getLogger(ResearchContainer_Test.class.getName()).log(Level.SEVERE, null, ex);
//        }

        dt.initDataTract();
        ec.addExp(new Experiment("test_exp"));
        dt.setCurExp(ec.getExp(0));
        ri = new ResearchInterpreter(dt);
        ri.setSysOut(list_outstream);
        jl_researchs.setModel(rc.getResearches());
        jl_researchs.addMouseListener(ml_listresearchers);


        /*rc.addReseach(new Research("test", "input.input(\"Слагаемое 1\",T_FLOAT,\"a\",1.0);\n"
         + "input.input(\"Слагаемое 2\",T_FLOAT,\"b\",2.0);\n"
         + "input.setInputs();\n"
         + "print(\"test\");"));
         rc.addReseach(new Research("aprox", "print(\"HA4AJIO\");\n"
         + "data.startBuildExp();\nprint(\"C6op uH<|>OPMAILuu...\");\n"
         + "Thread.sleep(2000);\n"
         + "print(\"3aBEPIIIEHuE C6OPA uH<|>OPMAILuu...\");\n"
         + "data.stopBuildExp();\nprint(\"C6OP uH<|>OPMAILuu 3aBEPIIIEH."
         + " O6HOBJIEHuE IIPOILECCA\");\n"
         + "exp.updateDataSensors();\n"
         + "proc.setProcess(exp.getFunc(0,0).getValues(),exp.getFunc(0,0).getArgs());\n"
         + "exp.addFunc(new Func(\"Апроксимация\","
         + "Func.F_OTHER,proc.approximateFunc("
         + "exp.getFunc(0,0).getArgs(),exp.getFunc(0,0).getValues()))"
         + ",0);\n"
         + "exp.addParam( new Param(\"Mean\",Param.P_OTHER,   proc.getMean() ) ,0   );"));*/
        rc.loadReseachesFromDirectory();
        jl_console.setModel(list_outstream.getListModel());
        /*list_outstream.getListModel().addListDataListener(new ListDataListener() {
            @Override
            public void intervalAdded(ListDataEvent e) {
                jl_console.setSelectedValue(jl_console.getModel().
                        getElementAt(jl_console.getModel().getSize() - 1), true);
            }

            @Override
            public void intervalRemoved(ListDataEvent e) {
            }

            @Override
            public void contentsChanged(ListDataEvent e) {
            }
        });*/
        this.setSize(700, 1000);
        this.setLocationRelativeTo(null);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane3 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jScrollPane4 = new javax.swing.JScrollPane();
        jl_console = new javax.swing.JList();
        jScrollPane1 = new javax.swing.JScrollPane();
        jl_researchs = new javax.swing.JList();
        jButton4 = new javax.swing.JButton();
        jScrollPane5 = new javax.swing.JScrollPane();
        ta = new javax.swing.JTextArea();

        jList1.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane3.setViewportView(jList1);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jButton1.setText("Run");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Save text");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Add");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jl_console.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jl_console.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jl_console.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jl_consoleMouseClicked(evt);
            }
        });
        jScrollPane4.setViewportView(jl_console);

        jl_researchs.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane1.setViewportView(jl_researchs);

        jButton4.setText("Viewer");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        ta.setColumns(20);
        ta.setRows(5);
        jScrollPane5.setViewportView(ta);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane4)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(241, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane5))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton1)
                    .addComponent(jButton3)
                    .addComponent(jButton4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane5)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 194, Short.MAX_VALUE)))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        rc.addResearch(new Research("trs", "print(\"trs\");"));
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        int si = jl_researchs.getSelectedIndex();
        if (si != -1) {
            rc.getResearch(si).setCode(ta.getText());
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        int si = jl_researchs.getSelectedIndex();
        if (si != -1) {
            try {
                ri.startResearch(rc.getResearch(si));
            } catch (EvalError ex) {
                Logger.getLogger(ResearchContainer_Test.class.getName())
                        .log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jl_consoleMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jl_consoleMouseClicked
        if (evt.getClickCount() == 2) {
            list_outstream.clear();
        }
    }//GEN-LAST:event_jl_consoleMouseClicked

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        ViewerExperimentsModel_Test vemt = new ViewerExperimentsModel_Test(ec);
        vemt.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        vemt.pack();
        vemt.setVisible(true);
    }//GEN-LAST:event_jButton4ActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        Configurator.getConf().saveConfig();
    }//GEN-LAST:event_formWindowClosing

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ResearchContainer_Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ResearchContainer_Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ResearchContainer_Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ResearchContainer_Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ResearchContainer_Test().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JList jList1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JList jl_console;
    private javax.swing.JList jl_researchs;
    private javax.swing.JTextArea ta;
    // End of variables declaration//GEN-END:variables
}
